package com.pboc.shiro;


import com.pboc.entity.SysUser;
import com.pboc.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("shiroDbRealm")
public class ShiroDbRealm extends AuthorizingRealm {
    @Autowired
    private SysUserService sysUserService;

    /**
     * 认证回调函数, 登录时调用.
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        token.setRememberMe(true);
        String username = token.getUsername();
        String pwd=String.valueOf(token.getPassword());
        if (username == null) {
            throw new AccountException("用户名不能为空");
        }
        SysUser user = sysUserService.getByLoginName(token.getUsername());
        if (null == user) {
            throw new AccountException("用户名不存在");
        }
        if (user.getLoginPwd().equals(pwd)) {
            this.setSession("currectUser",user);
            return new SimpleAuthenticationInfo(user.getLoginName(), user.getLoginPwd(), username);
        } else {
            throw new AccountException("密码错误");
        }
    }

    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    private void setSession(Object key, Object value) {
        Subject currentUser = SecurityUtils.getSubject();
        if (null != currentUser) {
            Session session = currentUser.getSession();
            if (null != session) {
                session.setAttribute(key, value);
            }
        }
    }

}